package com.xinhua.control;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.xinhua.entity.Courses;
import com.xinhua.entity.Major;
import com.xinhua.entity.Period;
import com.xinhua.entity.Student;
import com.xinhua.entity.SurveyContent;
import com.xinhua.entity.SurveyDetail;
import com.xinhua.entity.SurveyItem;
import com.xinhua.entity.Teacher;
import com.xinhua.service.CoursesService;
import com.xinhua.service.MajorService;
import com.xinhua.service.PeriodService;
import com.xinhua.service.StudentService;
import com.xinhua.service.SurveyContentService;
import com.xinhua.service.SurveyDetailService;
import com.xinhua.service.SurveyItemService;
import com.xinhua.service.TeacherService;

@RestController /* 所有方法返回的都是json对象 */
public class Survey {
	private List<SurveyItem> sitem;
	private List<Major> major;
	private List<Courses> course;
	private List<Teacher> teach;
	private List<SurveyDetail> sdetail;
	private List<Student> student;
	private List<Period> periods;
	private List<SurveyContent> surconts;

	@Autowired
	private SurveyItemService sis;
	@Autowired
	private SurveyContentService scs;
	@Autowired
	private MajorService ms;
	@Autowired
	private CoursesService cs;
	@Autowired
	private TeacherService ts;
	@Autowired
	private SurveyDetailService sdc;
	@Autowired
	private StudentService ss;
	@Autowired
	private PeriodService ps;

	@RequestMapping("/GetUserName")
	public String userNameInfo(@RequestParam("username") Integer name) {
		boolean isHave = false;
		student = ss.getStudent();
		for (Student stu : student) {
			if (stu.getId().equals(name)) {
				isHave = true;
			}
		}

		if (!isHave) {
			return "NoUser";
		} else {
			return "UserExist";
		}
	}

	@RequestMapping("/GetLogin")
	public String loginInfo(@RequestParam("username") Integer name, @RequestParam("pwd") String password,
			HttpServletRequest req) {
		boolean isDo = false;
		student = ss.getStudent();
		for (Student stu : student) {
			if (stu.getId().equals(name) && stu.getSecret().equals(password)) {
				isDo = true;
			}
		}
		if (!isDo) {
			return "ErrorPassword";
		} else {
			HttpSession session = req.getSession(true);
			session.setAttribute("username", name);
			return "Successful";
		}
	}

	@RequestMapping("/GetPeriod")
	@ResponseBody
	public Period getPeriod(HttpServletRequest req) {
		periods = ps.getPeriod();
		Period curPeriod = periods.get(periods.size() - 1);
		HttpSession session = req.getSession();
		session.setAttribute("periodname", curPeriod);
		return curPeriod;
	}

	@RequestMapping("/GetSurCont")
	public List<SurveyItem> getItem() {
		sitem = sis.getSurveyItem();
		return sitem;
	}

	@RequestMapping("/GetMajor")
	public Major getMajor(HttpServletRequest req) {
		HttpSession session = req.getSession();
		Integer stuid = (Integer) session.getAttribute("username");
		Major mj = null;
		student = ss.getStudent();
		for (Student stu : student) {
			if (stu.getId().equals(stuid)) {
				mj = stu.getMajor();
			}
		}
		session.setAttribute("majorname", mj);
		return mj;
	}

	@RequestMapping("/GetCourse")
	@ResponseBody
	public List<Courses> getCourse(HttpServletRequest req, @RequestParam("majorname") String name) {
		boolean ishas = true;
		major = ms.getMajor();
		List<Courses> cours = new ArrayList<>();
		for (int i = 0; i < major.size(); i++) {
			if (major.get(i).getName().equals(name)) {
				List<Courses> courses = major.get(i).getCourse();
				for (Courses course : courses) {
					for (Courses course1 : cours) {
						if (course.getName().equals(course1.getName())) {
							ishas = false;
						}
					}
					if (ishas)
						cours.add(course);
					ishas = true;
				}
			}
		}
		return cours;
	}

	@RequestMapping("/GetTeacher")
	@ResponseBody
	public List<Teacher> getTeacher(HttpServletRequest req, @RequestParam("coursename") String name) {
		boolean ishas = true;
		String[] courseArray = name.split(",");
		course = cs.getCourse();
		List<Courses> subTea = new ArrayList<>();
		List<Teacher> teachers = new ArrayList<>();
		for (int i = 0; i < courseArray.length; i++) {
			for (int j = 0; j < course.size(); j++) {
				if (course.get(j).getName().equals(courseArray[i])) {
					subTea.add(course.get(j));
					List<Teacher> teas = course.get(j).getTeacher();
					for (Teacher teacher : teas) {
						for (Teacher teacher1 : teachers) {
							if (teacher.getName().equals(teacher1.getName())) {
								ishas = false;
							}
						}
						if (ishas)
							teachers.add(teacher);
						ishas = true;
					}
				}
			}
		}
		HttpSession session = req.getSession();
		session.setAttribute("coursenames", subTea);
		return teachers;
	}

	@RequestMapping("/SetTeacher")
	public void setTeacher(HttpServletRequest req, @RequestParam("teachername") String name) {
		String[] teaArray = name.split(",");
		teach = ts.getTeacher();
		List<Teacher> teahs = new ArrayList<>();
		for (int i = 0; i < teaArray.length; i++) {
			for (Teacher teacher : teach) {
				if (teacher.getName().equals(teaArray[i])) {
					teahs.add(teacher);
				}
			}
		}
		HttpSession session = req.getSession();
		session.setAttribute("teachernames", teahs);
	}

	@RequestMapping("/SetSurDetail")
	public String submitInfo(HttpServletRequest req, @RequestParam("content_id") String contentid,
			@RequestParam("score") String score, @RequestParam("areaname") String areaVal) {
		try {
			HttpSession session = req.getSession();
			Period period = (Period) session.getAttribute("periodname");// 获得客户端评分的调查项目期数
			Major mjname = (Major) session.getAttribute("majorname"); // 获取客户端选择的评分专业
			@SuppressWarnings("unchecked")
			List<Courses> cours = (List<Courses>) session.getAttribute("coursenames"); // 获取客户端选择的评分课程
			@SuppressWarnings("unchecked")
			List<Teacher> teas = (List<Teacher>) session.getAttribute("teachernames"); // 获取客户端选择的评分教师
			String[] contents = contentid.split(","); // 获取客户端提交的调查内容并转化成数组
			String[] scores = score.split(","); // 获取客户端提交的调查内容所对应的评分分数

			String ip = null;
			// 获取客户端的ip地址，并作为客户端评分标识符存入数据库
			if (req.getHeader("x-forward-for") == null) {
				ip = req.getRemoteAddr();
				ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
			}

			// 通过客户端的ip地址,期数,课程，教师判断客户端提交的ip地址是否已经投过票
			sdetail = sdc.getSurveyDetail();
			for (SurveyDetail sd : sdetail) {
				for (Courses sessioncour : cours) {
					for (Teacher sessiontea : teas) {
						if (sd.getIp().equals(ip) && sd.getPd().getPeriod().equals(period.getPeriod())
								&& sd.getCourse().getId().equals(sessioncour.getId())
								&& sd.getTeacher().getId().equals(sessiontea.getId())) {
							throw new Exception("voted");
						}
					}
				}
			}

			boolean isDo = false;
			surconts = scs.getSurveyContent();
			for (int i = 0; i < cours.size(); i++) {
				List<Teacher> teache = cours.get(i).getTeacher();
				for (Teacher subt : teas) {
					for (Teacher t : teache) {
						if (subt.getName().equals(t.getName()))
							isDo = true;
					}
					if (isDo) {
						for (int j = 0; j < contents.length; j++) {
							SurveyDetail surdet = new SurveyDetail();
							for (SurveyContent surveycont : surconts) {
								if (surveycont.getId().equals(Integer.valueOf(contents[j]))) {
									surdet.setContent(surveycont);// 设置评分的项目内容id
								}
							}
							surdet.setScore(Integer.valueOf(scores[j])); // 设置评分内容对应的分数
							surdet.setIp(ip); // 设置客户端的ip
							surdet.setDate(new Date());// 设置客户端提交时间
							surdet.setMajor(mjname);// 设置客户端评分专业
							surdet.setPd(period);// 设置客户端评分期数
							surdet.setTeacher(subt); // 设置评分的教师id
							surdet.setCourse(cours.get(i)); // 设置评分的课程id
							surdet.setAdvise(areaVal); // 设置客户端提交的建议
							for (SurveyContent incont : surconts) {
								if (incont.getId().equals(Integer.valueOf(contents[j]))) {
									surdet.setItem(incont.getSurveyItem());// 设置客户端评分内容对应的调查项目id
								}
							}
							sdc.save(surdet);
						}
					}
					isDo = false;
				}
			}
			return "successful";
		} catch (Exception e) {
			if (e.getMessage().equals("voted")) {
				return "voted";
			} else {
				return "unsuccessful";
			}
		}
	}

	public List<Student> getStudent() {
		return student;
	}

}
